package guanli;

import until.DBUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class LockerManagePanel extends JPanel {
    private JTable table;
    private DefaultTableModel model;

    public LockerManagePanel() {
        setLayout(new BorderLayout());

        model = new DefaultTableModel(new Object[]{"ID", "柜体编号", "柜门编号", "尺寸", "状态"}, 0);
        table = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("添加");
        JButton deleteButton = new JButton("删除");
        JButton updateButton = new JButton("修改");
        JButton refreshButton = new JButton("刷新"); // 新增刷新按钮
        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(refreshButton); // 添加到按钮面板
        add(buttonPanel, BorderLayout.SOUTH);

        loadLockers();

        addButton.addActionListener(e -> addLocker());
        deleteButton.addActionListener(e -> deleteLocker());
        updateButton.addActionListener(e -> updateLocker());
        refreshButton.addActionListener(e -> loadLockers()); // 绑定刷新事件
    }

    private void loadLockers() {
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM lockers";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            model.setRowCount(0); // 清空原有数据
            while (rs.next()) {
                int id = rs.getInt("id");
                String cabinetNumber = rs.getString("cabinet_number");
                int doorNumber = rs.getInt("door_number");
                String size = rs.getString("size");
                String status = rs.getString("status");
                model.addRow(new Object[]{id, cabinetNumber, doorNumber, size, status});
            }
            rs.close();
            ps.close();
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载柜门信息失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void addLocker() {
        JTextField cabinetField = new JTextField();
        JTextField doorField = new JTextField();
        JComboBox<String> sizeBox = new JComboBox<>(new String[]{"小柜", "中柜", "大柜"});
        JComboBox<String> statusBox = new JComboBox<>(new String[]{"空闲", "占用", "故障"});

        JPanel panel = new JPanel(new GridLayout(0, 1));
        panel.add(new JLabel("柜体编号:"));
        panel.add(cabinetField);
        panel.add(new JLabel("柜门编号:"));
        panel.add(doorField);
        panel.add(new JLabel("尺寸:"));
        panel.add(sizeBox);
        panel.add(new JLabel("状态:"));
        panel.add(statusBox);

        int result = JOptionPane.showConfirmDialog(this, panel, "添加柜门", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            try (Connection conn = DBUtil.getConnection()) {
                String sql = "INSERT INTO lockers (cabinet_number, door_number, size, status) VALUES (?, ?, ?, ?)";
                PreparedStatement ps = conn.prepareStatement(sql);
                ps.setString(1, cabinetField.getText().trim());
                ps.setInt(2, Integer.parseInt(doorField.getText().trim()));
                ps.setString(3, (String) sizeBox.getSelectedItem());
                ps.setString(4, (String) statusBox.getSelectedItem());
                ps.executeUpdate();
                ps.close();
                loadLockers();
                JOptionPane.showMessageDialog(this, "添加成功！");
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "添加失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void deleteLocker() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) {
            int lockerId = (int) model.getValueAt(selectedRow, 0);
            int confirm = JOptionPane.showConfirmDialog(this, "确定删除柜门 ID " + lockerId + " 吗？", "确认删除", JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                try (Connection conn = DBUtil.getConnection()) {
                    String sql = "DELETE FROM lockers WHERE id = ?";
                    PreparedStatement ps = conn.prepareStatement(sql);
                    ps.setInt(1, lockerId);
                    ps.executeUpdate();
                    ps.close();
                    loadLockers();
                    JOptionPane.showMessageDialog(this, "删除成功！");
                } catch (Exception e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this, "删除失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择要删除的行。", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    private void updateLocker() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) {
            int lockerId = (int) model.getValueAt(selectedRow, 0);
            String cabinetNumber = (String) model.getValueAt(selectedRow, 1);
            int doorNumber = (int) model.getValueAt(selectedRow, 2);
            String size = (String) model.getValueAt(selectedRow, 3);
            String status = (String) model.getValueAt(selectedRow, 4);

            JTextField cabinetField = new JTextField(cabinetNumber);
            JTextField doorField = new JTextField(String.valueOf(doorNumber));
            JComboBox<String> sizeBox = new JComboBox<>(new String[]{"小柜", "中柜", "大柜"});
            sizeBox.setSelectedItem(size);
            JComboBox<String> statusBox = new JComboBox<>(new String[]{"空闲", "占用", "故障"});
            statusBox.setSelectedItem(status);

            JPanel panel = new JPanel(new GridLayout(0, 1));
            panel.add(new JLabel("柜体编号:"));
            panel.add(cabinetField);
            panel.add(new JLabel("柜门编号:"));
            panel.add(doorField);
            panel.add(new JLabel("尺寸:"));
            panel.add(sizeBox);
            panel.add(new JLabel("状态:"));
            panel.add(statusBox);

            int result = JOptionPane.showConfirmDialog(this, panel, "修改柜门信息", JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.OK_OPTION) {
                try (Connection conn = DBUtil.getConnection()) {
                    String sql = "UPDATE lockers SET cabinet_number = ?, door_number = ?, size = ?, status = ? WHERE id = ?";
                    PreparedStatement ps = conn.prepareStatement(sql);
                    ps.setString(1, cabinetField.getText().trim());
                    ps.setInt(2, Integer.parseInt(doorField.getText().trim()));
                    ps.setString(3, (String) sizeBox.getSelectedItem());
                    ps.setString(4, (String) statusBox.getSelectedItem());
                    ps.setInt(5, lockerId);
                    ps.executeUpdate();
                    ps.close();
                    loadLockers();
                    JOptionPane.showMessageDialog(this, "更新成功！");
                } catch (Exception e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this, "更新失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择要修改的行。", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }
}